﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Xml.Linq;
using System.Windows.Data;
using System.Reflection;

namespace Twi.COMMON.WPF
{
    public abstract class DialogInputBox : UserControl, IChildElement 
    {
        private static Dictionary<Type, BindingExpression[]> _bindingExpressionDic = new Dictionary<Type,BindingExpression[]>();

        #region IChildElement 成员

        public BindingExpression[] GetBindingExpression()
        {
            Type childType = this.GetType();
            if (!_bindingExpressionDic.ContainsKey(childType))
            {
                _bindingExpressionDic.Add(childType, this.GetType().GetFields(BindingFlags.Public | BindingFlags.Static)
                .Where(f => f.FieldType == typeof(DependencyProperty))
                .Select(f => this.GetBindingExpression((f.GetValue(null) as DependencyProperty))).ToArray());
            }
            return _bindingExpressionDic[childType];

        }

        public string[] GetBindingXElementName()
        {
            return null;
        }
        protected Button _btnSelect;

        protected virtual void InitializeSelectButton(Button btnSelect)
        {
            _btnSelect = btnSelect;
            _btnSelect.Click += _btnSelect_Click;
        }

        void _btnSelect_Click(object sender, RoutedEventArgs e)
        {
            OpenDialogBox();
        }

        protected Window _selector;

        protected void _selector_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _selector.Visibility = Visibility.Collapsed;
            e.Cancel = true;
        }

        /// <summary>
        /// 根据弹出对话窗口(_selector)中选中的值填充本控件中相关属性
        /// </summary>
        protected abstract void PopulateSelectedValue();

        /// <summary>
        /// 初始化弹出对话窗口(_selector)
        /// </summary>
        protected abstract void InitializeSelector();

        public void OpenDialogBox()
        {
            if (_selector == null)
            {                
                InitializeSelector();
                _selector.Closing += _selector_Closing;
            }
            _selector.ShowDialog();
            if (_selector.Visibility == Visibility.Collapsed && (_selector as ISelector).GetSelected() != null)//弹出对话窗口(_selector)选中记录并关闭后
            {
                PopulateSelectedValue();
            }
        }

        #endregion
    }

    /// <summary>
    /// 弹出对话框输入控件基类，依赖属性的绑定字段Mode必须是TwoWay
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class DialogInputBox<T> : DialogInputBox where T : Window, ISelector, new()
    {
        protected override void InitializeSelector()
        {
            _selector = new T();
        }
    }

}
